using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Autofac.Extensions.DependencyInjection;
using Infrastructure.Log;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NLog.Web;

namespace AdminApi
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration(config => {
                    var fullpath = typeof(Program).Assembly.Location;
                    var index = fullpath.LastIndexOf("/");
                    if (index < 0)
                    {
                        index = fullpath.LastIndexOf("\\");
                    }
                    string dir = fullpath.Substring(0, index);

                    foreach (var item in Directory.GetFiles(dir, "config_*.json"))
                    {
                        config.AddJsonFile(item);
                    }
                })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                })
                .UseServiceProviderFactory(new AutofacServiceProviderFactory())
                .ConfigureLogging(logging =>
                {
                    var config = logging.Services.First(i => i.ServiceType == typeof(IHostEnvironment));
                    logging.ClearProviders();
                    logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
                    logging.AddGoLifeLog(((IHostEnvironment)config.ImplementationInstance));

                }).UseNLog();
    }
}
